<?php
namespace app\admin\model;

class Business extends Base{

    protected $name = 'business_assess';
    const ASSSESS_TYPE = ['pe','pb','ps','pcf', 'company_total','total','take','profit','ev','growth'];
    public function initialize(){

    	$this->businessDb = db('business_assess');
        $this->securities = db('securities');
    }

    public function businessList($where=[]){

        $reArr = [];
        $reArr = $this->securities->where($where)->order('sid DESC')->select();
        foreach ($reArr AS $k=>$v){

            $tmp = [];
            $tmp = $this->businessDetail(['sid'=>$v['sid']]);
            $reArr[$k] = array_merge($reArr[$k], $tmp);
        }
        return $reArr;
    }

    public function delStockBusiness($id=0, $stock_code='',$arr=[]){
        $this->securities->where(['sid'=>$id])->update($arr);
    }

    public function delBusiness($id=0, $stock_code=''){
        $this->where(['sid'=>$id])->delete();
    }

    public function businessDetail($where=[]){

        $list = [];
    	$list = $this->businessDb->where($where)->select();
        $reVal = [];
        foreach ($list AS $k=>$v) {

            foreach (self::ASSSESS_TYPE AS $vv) {

                if($v['assess_type']==$vv){

                    $reVal[$v['assess_type']] = $v['val'];
                    $reVal[$v['assess_type'].'_average'] = $v['mean_val'];
                    $reVal[$v['assess_type'].'_rank'] = $v['status'];
                    $reVal[$v['assess_type'].'_company_total'] = $v['company_total'];
                }
            }
        }
        return $reVal;
    }

    public function addBusiness($arr=[]){
        $this->edit($arr);
    }

    public function edit($data=[]) {
        foreach(self::ASSSESS_TYPE AS $v) {
            $tmp = [];
            $tmp['sid'] = $data['sid'];
            $tmp['stock_code'] = $data['stock_code'];
            $tmp['assess_type'] = $v;
            $tmp['mean_val'] = !empty($data[$v.'_average']) ? trim($data[$v.'_average']) : 0 ;
            $tmp['val'] = !empty($data[$v]) ? trim($data[$v]) : 0 ;
            $tmp['status'] = !empty($data[$v.'_rank']) ? trim($data[$v.'_rank']) : 0 ;
            $tmp['company_total'] = !empty($data[$v.'_company_total']) ? trim($data[$v.'_company_total']) : 0 ;
            $this->saveAdd($data['sid'], $data['stock_code'], $tmp);
        }
    }

    //是否存在
    protected function saveAdd($sid=0, $stock_code='', $arr=[]){
        $exist = null;
        $where = ['sid'=>$sid, 'stock_code'=>$stock_code, 'assess_type'=>$arr['assess_type']];
        $exist = $this->where($where)->find();
        if($exist == NULL){
            $this->insert($arr);
        }else{
            $this->where($where)->update($arr);
        }
    }
}